//
//  DJDetailViewController.m
//  CoolFM
//
//  Created by 曹曹 on 16/9/2.
//  Copyright © 2016年 曹曹. All rights reserved.
//

#import "DJDetailViewController.h"
// tool
#import "CFMacro.h"
#import "UIImageView+WebCache.h"
#import "UIView+Frame.h"
#import "GXNetTool.h"
#import "NSString+GX_MD5.h"
#import "NSString+URLEncode.h"
// tableView cell
#import "DJDetailProgramTableViewCell.h"
// CollectionView cell
#import "DJDetailAlbumCollectionViewCell.h"
#import "DJDetailProgramCollectionViewCell.h"
#import "DJDetailCommentCollectionViewCell.h"
// pop三方
#import "UINavigationController+FDFullscreenPopGesture.h"
// dj model
#import "Dj_Info.h"
// album model
#import "AlbumRoot.h"
#import "AlbumRecord.h"
#import "AlbumRecord_Plays.h"
#import "AlbumRecord_Dj_Info.h"
// program model
#import "DJProgramRoot.h"
#import "DJProgramRecords.h"
// comment model
#import "DJDetailComment.h"
#import "Comment.h"
#import "Reply.h"

#define kDJDetailAlbumCollectionViewCell @"DJDetailAlbumCollectionViewCell"
#define kDJDetailProgramCollectionViewCell @"DJDetailProgramCollectionViewCell"
#define kDJDetailCommentCollectionViewCell @"DJDetailCommentCollectionViewCell"

@interface DJDetailViewController () <UICollectionViewDelegate, UICollectionViewDataSource>

// 关注按钮
@property (weak, nonatomic) IBOutlet UIButton *focusButton;
// dj 背景
@property (weak, nonatomic) IBOutlet UIImageView *backImage;
// dj 头像
@property (weak, nonatomic) IBOutlet UIImageView *frontImage;
// dj 昵称
@property (weak, nonatomic) IBOutlet UILabel *djNick;
// dj 介绍
@property (weak, nonatomic) IBOutlet UILabel *detail;
// dj 人气
@property (weak, nonatomic) IBOutlet UILabel *listener;
// CollectionView
@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
// layout
@property (weak, nonatomic) IBOutlet UICollectionViewFlowLayout *layout;
// 专辑按钮
@property (weak, nonatomic) IBOutlet UIButton *albumButton;
// 节目按钮
@property (weak, nonatomic) IBOutlet UIButton *programButton;
// 留言板按钮
@property (weak, nonatomic) IBOutlet UIButton *commentButton;
// 指示线
@property (weak, nonatomic) IBOutlet UIView *lineView;
// 切换CollectionView的按钮菜单
@property (weak, nonatomic) IBOutlet UIView *menuView;
// V icon
@property (weak, nonatomic) IBOutlet UIImageView *dj_V_imageView;
// 改变navigationBar颜色用
@property (nonatomic, assign) CGFloat topContentInset;
@property (nonatomic, assign) CGFloat alphaMemory;
// 三方需要使用的视图
@property (weak, nonatomic) IBOutlet UIView *blurView;
// 头视图动画开关
@property (nonatomic, assign) BOOL isPriorityChanged;
// model
@property (nonatomic, strong) AlbumRoot *album;
@property (nonatomic, strong) DJProgramRoot *program;
@property (nonatomic, strong) DJDetailComment *rootComment;

@end

@implementation DJDetailViewController

- (IBAction)tapImageView:(id)sender {
    if (_isPriorityChanged) {
        [UIView animateWithDuration:0.5 animations:^{
            _frontImage.transform = CGAffineTransformIdentity;
            _dj_V_imageView.transform = CGAffineTransformIdentity;
            _djNick.transform = CGAffineTransformIdentity;
            _detail.gx_y = _djNick.gx_y + 40;
            // 默认高度为12
            _detail.gx_height = 12;
            _isPriorityChanged = 0;
        }];
    } else {
        [UIView animateWithDuration:0.5 animations:^{
            _frontImage.transform = CGAffineTransformMakeTranslation(0, -120);
            _dj_V_imageView.transform = CGAffineTransformMakeTranslation(0, -120);
            _djNick.transform = CGAffineTransformMakeTranslation(0, -80);
            _detail.gx_y = _djNick.gx_y + 40;
            _detail.gx_height = _backImage.gx_height / 3.0;
            _isPriorityChanged = 1;
        }];
    }
}
#pragma mark - setter
- (void)setDj_info:(Dj_Info *)dj_info {
    _dj_info = dj_info;
    [self handleData];
}
#warning DJDetailViewController send noti
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"showCommentBar"
                                                        object:@"commentBar"
                                                      userInfo:nil];
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"showPlayerView"
                                                        object:@"playerView"
                                                      userInfo:nil];

}
#warning vc完全消失时发送了隐藏播放条的消息, 所以需要再次发送显示播放条的消息.有空了研究下原因
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"showPlayerView"
                                                        object:@"playerView"
                                                      userInfo:nil];
}

#pragma mark - viewDidLoad
- (void)viewDidLoad {
    [super viewDidLoad];
    // 判断动画状态开关
    self.isPriorityChanged = 0;
    // 隐藏navigationBar - 三方
    self.fd_prefersNavigationBarHidden = YES;
    // 处理数据
    [self handleData];
    // 圆角处理头像和关注按钮
    [self roundRect];
    // 毛玻璃背景头像
    [self blurImageView];
    // 给头视图控件赋值
    [self setValuesForSubViews];
    // 设置CollectionView
    [self configCollectionView];
}
#pragma mark - 请求数据
- (void)handleData {
    // 获取主播的专辑数据
    NSString *djDetailAlbumURL =  [NSString stringWithFormat:@"http://api.kufm.cn/v3/playback/get_dj_total_play/list_info?dj_id=%ld&dj_name=%@", _dj_info.dj_id, [_dj_info.dj_name URLEncodeString]];
    [GXNetTool GET:djDetailAlbumURL
           andBody:nil
         andHeader:nil
       andResponse:GXJSON
   andSuccessBlock:^(id result) {
        AlbumRoot *root = [AlbumRoot modelWithDictionary:result];
        self.album = root;
        [self.collectionView reloadData];
    } andFailureBlock:^(NSError *error) {
        NSLog(@"失败");
    }];
    
    // 获取主播的节目数据
    NSString *djDetailProgramURL = [NSString stringWithFormat:@"http://api.kufm.cn/v3/playback/get_dj_total_record/list_info?dj_id=%ld&page_index=1&page_size=20", _dj_info.dj_id];
    [GXNetTool GET:djDetailProgramURL
           andBody:nil
         andHeader:nil
       andResponse:GXJSON
   andSuccessBlock:^(id result) {
        DJProgramRoot *program = [DJProgramRoot modelWithDictionary:result];
        self.program = program;
        [self.collectionView reloadData];
    } andFailureBlock:^(NSError *error) {
        NSLog(@"失败");
    }];
    
    // 获取主播的留言板数据
    NSString *djDitailCommentURL = [NSString stringWithFormat:@"http://api.kufm.cn/v3/playback/dj/message_board/get_comment/%ld/list_info?page_size=20&page_index=1", _dj_info.dj_id];
    [GXNetTool GET:djDitailCommentURL
           andBody:nil andHeader:nil
       andResponse:GXJSON
   andSuccessBlock:^(id result) {
        DJDetailComment *comment = [DJDetailComment modelWithDictionary:result];
        self.rootComment = comment;
        [self.collectionView reloadData];
    } andFailureBlock:^(NSError *error) {
        NSLog(@"失败");
    }];
}
#pragma mark - 设置CollectionView
- (void)configCollectionView {
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    CGFloat menuViewH = 30;
    _layout.itemSize = CGSizeMake(SCREEN_WIDTH, SCREEN_HEIGHT * 2 / 3.0 - 49 - menuViewH);
    _layout.minimumLineSpacing = 0;
    _layout.minimumInteritemSpacing = 0;
    _layout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
    // 注册cell
    kCollectionViewRegisterNib(@"DJDetailAlbumCollectionViewCell", kDJDetailAlbumCollectionViewCell);
    kCollectionViewRegisterNib(@"DJDetailProgramCollectionViewCell", kDJDetailProgramCollectionViewCell);
    kCollectionViewRegisterNib(@"DJDetailCommentCollectionViewCell", kDJDetailCommentCollectionViewCell);
    // 添加观察者, 完成操作后需要移除观察者
    [_collectionView addObserver:self
                      forKeyPath:@"contentOffset"
                         options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld
                         context:@"ccc"];
}
#pragma mark - round 头像
- (void)roundRect {
    _frontImage.layer.cornerRadius = SCREEN_HEIGHT / 18.0;
    _frontImage.layer.masksToBounds = YES;
    _focusButton.layer.cornerRadius = 2;
    _focusButton.layer.borderWidth = 1;
    _focusButton.layer.borderColor = kDefaultColor.CGColor;
}
#pragma mark - blur背景
- (void)blurImageView {
    UIBlurEffect *blur = [UIBlurEffect effectWithStyle:UIBlurEffectStyleDark];
    UIVisualEffectView *effectview = [[UIVisualEffectView alloc] initWithEffect:blur];
    effectview.frame = CGRectMake(0, 0, _backImage.gx_width, SCREEN_HEIGHT / 3.0);
    [_backImage addSubview:effectview];
    
}
#pragma mark - 给DJ头视图信息赋值
- (void)setValuesForSubViews {
    [_backImage sd_setImageWithURL:[NSURL URLWithString:_dj_info.dj_image_url]
                  placeholderImage:[UIImage imageNamed:@"icon_dj"]];
    [_frontImage sd_setImageWithURL:[NSURL URLWithString:_dj_info.dj_image_url]
                   placeholderImage:[UIImage imageNamed:@"icon_dj"]];
    _djNick.text = _dj_info.dj_name;
    _detail.text = _dj_info.dj_summary;
    _listener.text = [NSString stringWithFormat:@"人气: %ld", _dj_info.dj_popularity];
}
#pragma mark - 返回按钮点击事件
- (IBAction)backButtonClicked:(id)sender {
//    [self.navigationController popToRootViewControllerAnimated:YES];
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark - collectionView 代理
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return 3;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        DJDetailAlbumCollectionViewCell *albumCell = [collectionView dequeueReusableCellWithReuseIdentifier:kDJDetailAlbumCollectionViewCell forIndexPath:indexPath];
        if (_album) {
            albumCell.album = _album;
        }
        return albumCell;
    } else if (indexPath.row == 1) {
        DJDetailProgramCollectionViewCell *programCell = [collectionView dequeueReusableCellWithReuseIdentifier:kDJDetailProgramCollectionViewCell forIndexPath:indexPath];
        if (_program) {
            programCell.program = _program;
        }
        return programCell;
    } else {
        DJDetailCommentCollectionViewCell *commentCell = [collectionView dequeueReusableCellWithReuseIdentifier:kDJDetailCommentCollectionViewCell forIndexPath:indexPath];
        if (_rootComment) {
            commentCell.rootComment = _rootComment;
        }
        return commentCell;
    }
}
#pragma mark - KVO 检测偏移量
- (void)observeValueForKeyPath:(NSString *)keyPath
                      ofObject:(id)object
                        change:(NSDictionary<NSString *,id> *)change
                       context:(void *)context {
    for (UIView *view in self.menuView.subviews) {
        if ([view isKindOfClass:[UIButton class]]) {
            UIButton *btn = (UIButton *)view;
            [btn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
            btn.titleLabel.font = kFont11;
        }
    }
    CGFloat newX = [[change objectForKey:@"new"] CGPointValue].x;
    NSInteger newTag = (newX + SCREEN_WIDTH / 2) / SCREEN_WIDTH;
    UIButton *button = [self.menuView viewWithTag:newTag + 20];
    [button setTitleColor:kDefaultColor forState:UIControlStateNormal];
    button.titleLabel.font = [UIFont systemFontOfSize:15];
    _lineView.gx_x = newX / 3;
#warning DJDetailViewController send noti
    if (newX == SCREEN_WIDTH * 2) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"hidePlayerView"
                                                            object:@"playerView"
                                                          userInfo:nil];
    } else {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"showPlayerView"
                                                            object:@"playerView"
                                                          userInfo:nil];
    }
}
#pragma mark - button 点击事件
- (IBAction)gotoAlbum:(id)sender {
    [_collectionView setContentOffset:CGPointMake(0, 0) animated:YES];
}
- (IBAction)gotoProgram:(id)sender {
    [_collectionView setContentOffset:CGPointMake(SCREEN_WIDTH, 0) animated:YES];
}
- (IBAction)gotoComment:(id)sender {
    [_collectionView setContentOffset:CGPointMake(SCREEN_WIDTH * 2, 0) animated:YES];
}
#warning 这个很重要, 一定要注意!!
#pragma mark - 移除观察者
- (void)dealloc {
    [_collectionView removeObserver:self forKeyPath:@"contentOffset"];
}
#pragma mark - others
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
